<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App;
use Cache, Artisan;

class Article extends Model
{

    const UPLOAD_DIR = 'uploads';
    protected $table='articles';

    protected $fillable = ['journal_id', 'issue_id', 'cate_id', 'page_start', 'page_end', 'cite_count', 'title', 'id_doi', 'author_list', 'affiliation', 'corresponding_info', 'abstract', 'keywords', 'fund', 'is_pic', 'is_featured', 'is_press', 'accept_date', 'revision_date', 'publish_date', 'pdf', 'xml', 'html', 'imgs', 'zr_id', 'cn_title', 'cn_author_list', '  cn_affiliation', 'cn_abstract', 'cn_keywords', 'xml_id', 'download_count', 'view_count'];

    public function getTitle()
    {
        if (App::getLocale() == 'cn' && $this->cn_title) {
            return $this->cn_title;
        }
        return $this->title;
    }

    public function getAuthorList()
    {
        if (App::getLocale() == 'cn' && $this->cn_author_list) {
            return $this->cn_author_list;
        }
        return $this->author_list;
    }

    public function getPureAuthor()
    {
        $author = preg_replace('/(<sup.*?sup>|,\S{1})|\*/', '', $this->author_list);

        return $author;
    }

    public function getAffiliation()
    {
        if (App::getLocale() == 'cn' && $this->cn_affiliation) {
            return $this->cn_affiliation;
        }
        return $this->affiliation;
    }

    public function getAbstract()
    {
        if (App::getLocale() == 'cn' && $this->cn_abstract) {
            return $this->cn_abstract;
        }
        return $this->abstract;
    }

    public function getKeywords()
    {
        if (App::getLocale() == 'cn' && $this->cn_keywords) {
            return $this->cn_keywords;
        }
        return $this->keywords;
    }

    public function setImgsAttribute($imgs)
    {
        if (is_array($imgs)) {
            $this->attributes['imgs'] = json_encode($imgs);
        }
    }
    
    public function getImgsAttribute($imgs)
    {
        return json_decode($imgs, true);
    }

    public function getFirstImg()
    {
        if (count($this->imgs) > 0) {
            return self::UPLOAD_DIR . '/' . $this->imgs[0];
        }
        return null;
    }

    public function journal()
    {
        return $this->belongsTo(Journal::class);
    }

    public function author()
    {
        return $this->author_list;
        // return $this->hasMany(Author::class);
    }

    public function authorWithoutAff()
    {
        // return $this->author_list;
        return trim(preg_replace('/(<.*?>.*?<\/.*?>|,\*)/', '', $this->author_list), ',');
    }

    // public function affiliation()
    // {
    //     return $this->hasMany(Affiliation::class);
    // }

    public function articleCat()
    {
        return $this->belongsTo(ArticleCat::class, 'cate_id', 'id');
    }

    // public function newsCat()
    // {
    //     return $this->belongsTo(NewsCat::class);
    // }

    public function issue()
    {
        return $this->belongsTo(Issue::class);
    }

    // public function getAutorNames($obj=null)
    // {
    //     if (!$obj) $obj = $this;
    //     $authors = $obj->author;
    //     $authors = array_map(function($author) {
    //         // print_r($author);exit;
    //         return $author->getName() . '<sup>' . $author->affiliation . '</sup>';
    //     }, $authors->all());
    //     return implode(', ', $authors);
    // }

    public function getKeywordsArr()
    {
        return preg_split('/;\s*/', $this->getKeywords());
    }

    public function getRelatedArticles()
    {
        return (new static())->orderBy('created_at', 'desc')->limit(6)->get();
    }

    public function fileSize($type = 'pdf')
    {
        $size = '0kb';
        switch ($type) {
            case 'pdf':
            if ($this->pdf) {
                if (file_exists($this->getFilePath())) {
                    $size =  round(filesize($this->getFilePath()) / 1024) . 'kb';
                }
            }
                break;

            default:
                return '0kb';
                break;

            return '0kb';
        }

        return $size;
    }


    public function getFilePath()
    {
        return public_path('uploads/' . $this->pdf);
    }

    public function getPrevId()
    {
        $id = $this->id;
        return $this->where('id', '<', $id)->max('id');
    }

    public function getNextId()
    {
        $id = $this->id;
        return  $this->where('id', '>', $id)->min('id');
    }

    public function pureAuthorList()
    {
        return strip_tags($this->author_list, '<sup>');
    }

    public function getUrl()
    {
        return route('article.index', ['id' => $this->id]);
    }


    public function getOldHtmlname()
    {
        return 'ZoolRes-' . $this->issue->volume . '-' . $this->issue->issue . '-' . $this->page_start . '.html';
    }

    public function newHtmlname()
    {
        return $this->xml_id . '.html';
    }


    public function getHtmlPath($dir)
    {
        $path = $dir . '/' . $this->issue->year;

        $newPath = $path . '/' . $this->issue->id . '/' . $this->newHtmlname();
        if (file_exists($newPath)) {
            return $newPath;
        }
        
        $oldPath = $path . '/' . $this->issue->zr_id . '/' . $this->getOldHtmlname();
        return $oldPath;
    }

    public function getHtmlUrl()
    {
        if ($this->html) {
            return $this->html;
        }
        return 'javascript:void(0)';
        return url('articles' . str_replace(config('app.html_dir'), '', $this->getHtmlPath(config('app.html_dir'))));
    }

    public static function mostDownload($count = 5)
    {
        return (new static())->latest()->orderBy('download_count', 'desc')->take($count)->get();
    }

    public static function mostView($count = 5)
    {
        return (new static())->latest()->orderBy('view_count', 'desc')->take($count)->get();
    }

    public static function mostCiteOnWOS($count=5)
    {
        return (new static())->latest()->orderBy('cite_count', 'desc')->take($count)->get();
    }

    public static function getBaiduCitesList()
    {
        $bList = Cache::get(config('app.cites_cahe_name'));

        if (count($bList) <= 0) {
            Artisan::call('sync:baidu:citation');
            $bList = Cache::get(config('app.cites_cahe_name'));
        }

        $ids = array_keys($bList);
        if (count($bList) <= 0) {
            return null;
        }

        return (new static())->whereIn('id', $ids)->take(5)->get();

    }
}
